<template>
  <div class="login-container">
    <h2>Register</h2>
    <el-form class="login-form">
      <el-form-item label="Username">
        <el-input v-model="username" placeholder="Enter your username"></el-input>
      </el-form-item>
      <el-form-item label="Password">
        <el-input type="password" v-model="password" placeholder="Enter your password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleRegister" class="Register-button">Register</el-button>
      </el-form-item>
      <div class="additional-actions">
        <el-link type="primary" @click="backLogin">Back Login</el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {ref} from 'vue';
import {ElForm, ElFormItem, ElInput, ElButton, ElLink} from 'element-plus';
//import 'element-plus/dist/index.css';

import {useRouter} from 'vue-router';

const router = useRouter();

import axios from 'axios';
import {urlData} from "@/utils/url.js"
import qs from 'qs';


const username = ref('');
const password = ref('');
import {ElMessage} from 'element-plus';

const backLogin = () => {
  // 返回登录页面
  ElMessage.success('点击返回登录');
  router.push('/login');
};

const handleRegister = async () => {
  // 处理注册逻辑
  ElMessage.info('点击了注册按钮');

  console.log('user===>', username.value, password.value);

  try {
    await axios.post(urlData("user/register"), qs.stringify({
      username: username.value,
      password: password.value
    })).then(res => {
          console.log('res===>', res);
          if (res.data.code === 200) {
            ElMessage.success('注册成功');
            router.push('/login');
          } else {
            console.log('res.data.msg===>', res.data.msg);
            ElMessage.error(res.data.msg);
          }
        }, error => {
          console.log('error===>', error);
          ElMessage.error(error.code);
        }
    )
  } catch (error) {
    ElMessage.error('注册失败');
    console.log('error===>', error);
  }


};

</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  height: 100vh;
  padding-top: 50px;
  background-color: #f5f5f5;
}

h2 {
  margin-bottom: 20px;
}

.login-form {
  width: 300px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #fff;
}

.additional-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.Register-button {
  width: 100%;
}
</style>